/*
Copyright 2021 LuJun

Permission is hereby granted, free of charge, to any person obtaining a copy 
of this software and associated documentation files (the "Software"), to deal 
in the Software without restriction, including without limitation the rights 
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
copies of the Software, and to permit persons to whom the Software is furnished 
to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in 
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/

/// <reference path="./lcc.ts" />

namespace lcc {

const TAG = "lcc/base/loading-module.ts";

/**
 * @zh
 * 加载模块数组
 */
const LoadingModules:LoadingModule[] = [];

/**
 * @zh
 * 加载模块
 */
export class LoadingModule extends __cc__.EventTarget {

	/**
	 * @zh
	 * 构造加载模块
	 */
	constructor(){
		super();
		LoadingModules.push(this);
	}
	
	/**
	 * @zh
	 * 标记表在加载中
	 */
	private _loading:boolean = false;

	/**
	 * @zh
	 * 当加载完成回调
	 */
	private _onLoaded:Function = null;
	
	/**
	 * @zh
	 * 设置加载状态
	 * 
	 * @param loading 
	 */
	protected setLoading(loading:boolean){
		this._loading = loading;
		if(!this._loading){
			if(this._onLoaded){
				let callback = this._onLoaded;
				this._onLoaded = null;
				callback();
			}
		}
	}

	/**
	 * @zh
	 * 检查数据表是否在加载中
	 */
	public isLoading(){
		return this._loading;
	}

	/**
	 * 等待加载完成
	 */
	public async waitLoading(){
		if(this._loading){
			return new Promise((resolve)=>{
				this._onLoaded = resolve;
			});
		}
	}
}

/**
 * @zh
 * 等待框架加载
 */
export async function waitLoading() {
	for (let module of LoadingModules){
		await module.waitLoading();
	}
}

}
